package com.qf.tenant.manager.service.impl;

import com.qf.common.bean.R;
import com.qf.common.dto.DeviceDto;
import com.qf.common.dto.ProductDto;
import com.qf.common.model.QfDevice;
import com.qf.common.model.QfDeviceTopic;
import com.qf.common.model.QfProduct;
import com.qf.common.utils.IdWorker;
import com.qf.tenant.manager.feign.DeviceFeign;
import com.qf.tenant.manager.feign.DeviceTopicFeign;
import com.qf.tenant.manager.feign.ProductFeign;
import com.qf.tenant.manager.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class DeviceServiceImpl implements DeviceService {

    @Autowired
    private DeviceFeign deviceFeign;

    @Autowired
    private DeviceTopicFeign deviceTopicFeign;

    @Autowired
    private ProductFeign productFeign;

    @Override
    public R<List> findByParentId(Long parentId) {
        DeviceDto dto = new DeviceDto();
        dto.setParentId(parentId);
        R<List> result = deviceFeign.findAreaAll(dto);
        return result;
    }

    @Override
    public R saveDevice(DeviceDto deviceDto) {
        /**
         * 1. 生成设备唯一的key叫做deviceKey
         * 规则: device_唯一id(雪花算法生成)
         */
        String deviceKey = "device_" + new IdWorker().nextId();
        deviceDto.setDeviceKey(deviceKey);

        //2. 设置创建时间, 更新时间, 逻辑删除状态, 设备激活状态, 默认为未激活
        deviceDto.setCreateTime(new Date());
        deviceDto.setUpdateTime(new Date());
        deviceDto.setDeleted(false);
        deviceDto.setActive(1);

        //3. 生成设备秘钥deviceSecuret, 设备秘钥可以使用随机字符串, 明文保存
        deviceDto.setDeviceSecret(UUID.randomUUID().toString().replace("-", ""));

        //4. 保存设备信息到数据库
        QfDevice qfDevice = new QfDevice();
        //dto转成pojo实体类
        deviceDto.convertDtoToDo(qfDevice);
        R<QfDevice> result = deviceFeign.add(qfDevice);

        //5. 生成由设备发往平台, 上报数据所用的Topic主题
        QfDeviceTopic qfDeviceTopic = new QfDeviceTopic();
        //设备唯一key
        qfDeviceTopic.setDeviceKey(qfDevice.getDeviceKey());
        qfDeviceTopic.setDeleted(false);
        qfDeviceTopic.setCreateTime(new Date());
        qfDeviceTopic.setUpdateTime(new Date());
        // 主题名称: /qfjava/device/data/deviceKey设备唯一key
        qfDeviceTopic.setTopic("/qfjava/device/data/" + qfDevice.getDeviceKey());
        deviceTopicFeign.add(qfDeviceTopic);

        //6. 生成由平台发给设备的Topic主题
        //主题名称: /qfjava/device/ctrl/deviceKey设备唯一key
        qfDeviceTopic.setTopic("/qfjava/device/ctrl/" + qfDevice.getDeviceKey());
        deviceTopicFeign.add(qfDeviceTopic);

        return result;
    }

    @Override
    public R listDeviceByTenantId(String tenantId) {
        R<List<DeviceDto>> r = deviceFeign.lisByTenant(tenantId);
        return r;
    }

    @Override
    public R listDevices(DeviceDto deviceDto) {
        deviceDto.setDeleted(false);
        return deviceFeign.list(deviceDto);
    }

    @Override
    public R delDevice(Long deviceId,String phone,String code) {

        //验证码正确,删除当前设备
        delDeviceById(deviceId);
        return R.ok("删除设备成功！");

    }



    @Override
    public R delDevice(Long deviceId) {
        try {
            delDeviceById(deviceId);
            return R.ok("删除设备成功！");
        }catch (Exception e){
            e.printStackTrace();
            return R.fail("删除设备失败！");
        }
    }

    @Override
    public R getDeviceById(String deviceId) {
        return deviceFeign.selectDetailById(deviceId);
    }

    @Override
    public R listDevices(Long productId) {
        DeviceDto deviceDto = new DeviceDto();
        deviceDto.setProductId(productId);
        deviceDto.setDeleted(false);
        R<List> r = deviceFeign.findAreaAll(deviceDto);
        return r;
    }

    @Override
    public R<Map<String, Integer>> selectDeviceCount(String tenantId, Long productId) {
        //统计设备总数
        DeviceDto dto = new DeviceDto();
        dto.setDeleted(false);
        dto.setTenantId(tenantId);
        if (productId != null && productId != 0) {
            dto.setProductId(productId);
        }
        R<Integer> allCount = deviceFeign.findAllCount(dto);

        //统计激活设备数据
        dto.setActive(2);
        R<Integer> activeCount = deviceFeign.findAllCount(dto);

        Map<String, Integer> resultMap = new HashMap<>();
        //总设备数
        resultMap.put("allCount", allCount.getData());
        //激活设备数
        resultMap.put("activeCount", activeCount.getData());
        //todo 在线设备数
        resultMap.put("onLineCount", 0);
        return R.ok(resultMap);
    }

    @Override
    public R listDevicesProduct(String productId) {
        return deviceFeign.lisByProduct(productId);
    }

    @Override
    public R listDevicesByTenant(String tenantId) {
        return deviceFeign.lisByTenant(tenantId);
    }



    @Override
    public R<List> findAll(DeviceDto deviceDto) {
        return deviceFeign.findAreaAll(deviceDto);
    }


    /**
     * 根据id删除设备：如果是子设备就直接删除，如果是父设备则先删除所有子设备再删除父设备
     * @param id
     */
    private void delDeviceById(Long id){
        //查询此设备是否有子设备
        DeviceDto deviceDto = new DeviceDto();
        deviceDto.setParentId(id);
        R<List> r = deviceFeign.findAreaAll(deviceDto);
        if(r.isOk() && r.getData().size() > 0){
            for (Object obj : r.getData() ) {
                QfDevice qfDevice = (QfDevice)obj;
                delDeviceById(qfDevice.getId());
            }
        }else{
            //执行设备逻辑删除
            R<QfDevice> r1 = deviceFeign.selectById(id + "");
            QfDevice qfDevice = r1.getData();
            qfDevice.setDeleted(true);
            deviceFeign.update(qfDevice);
        }
    }

}
